package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WxPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WxPayController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 支付下单
     * @param orderId
     * @param payMoney
     * @return
     */
    @GetMapping("/nativePay")
    public Result nativePay(@RequestParam("orderId") String orderId,@RequestParam("payMoney") Integer payMoney){
        // wxResult -> code_url 生成二维码的支付地址
        Map<String,Object> wxResult = wxPayService.nativePay(orderId,payMoney);
        return new Result(true, StatusCode.OK,"", wxResult);
    }

    //http://localhost:9010/wxpay/notify
    //http://limingxuan.cross.echosite.cn/wxpay/notify
    @RequestMapping("/notify")
    public void notifyMethod(HttpServletRequest request, HttpServletResponse response){
        System.out.println("微信支付回调方法 执行啦~~~");
        // TODO 提交订单,接收微信的通知消息
        try {
            //接收微信传递过来的输入流
            ServletInputStream inputStream = request.getInputStream();
            //将输入流转换成string
            String xml = ConvertUtils.convertToString(inputStream);
            System.out.println(xml);

            Map<String, String> map = WXPayUtil.xmlToMap(xml);

            //用户支付的结果
            //调用微信查询接口进行查询
            String orderId = map.get("out_trade_no");
            Map resultMap = wxPayService.queryOrder(orderId);
            System.out.println("订单查询结果 : "+resultMap);

            //判断此次查询是否成功
            if("SUCCESS".equals(resultMap.get("result_code"))){
                //查询订单成功

                //判断是否支付成功,或者判断业务是否成功
                if("SUCCESS".equals(resultMap.get("trade_state"))) {
                    System.out.println("支付成功...");
                    //将结果发送到rabbitmq,去更新数据库的订单状态,为已支付,记录微信的交易流水号,transaction_id
                    Map param = new HashMap();
                    param.put("out_trade_no",orderId);
                    param.put("transaction_id",resultMap.get("transaction_id"));
                    rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(param));
                    System.out.println("发送消息到消息队列中,进行更新操作!");

                    //发送消息到消息队列,通知页面跳转.
                    //参数orderId和支付金额
                    //浏览器就能够通过webSocket接收到该消息,浏览器发送请求,渲染微服务,进行成功页面的跳转.
                    rabbitTemplate.convertAndSend(RabbitMQConfig.PAY_NOTIFY,"",orderId);
                }else{
                    //支付失败
                    System.out.println(resultMap.get("err_code_des"));
                }

            }else{
                //查询失败
                System.out.println(resultMap.get("err_code_des"));
            }

            //给微信一个收到的结果,告诉微信我们已经收到你的通知啦,不用再发啦.
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            //设置响应头,内容格式为xml格式
            response.setContentType("text/xml");
            response.getWriter().write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/query/{orderId}")
    public Result queryOrder(@PathVariable("orderId") String orderId){
        Map map = wxPayService.queryOrder(orderId);
        return new Result(true,StatusCode.OK,"查询订单成功",map);
    }

    @PutMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable("orderId") String orderId){
        Map map = wxPayService.closeOrder(orderId);
        return new Result(true,StatusCode.OK,"关闭订单成功",map);
    }


}
